package bit.springblogdemo.service.impl;


import bit.springblogdemo.common.exception.BlogException;
import bit.springblogdemo.common.util.BeanUtilTrans;
import bit.springblogdemo.common.util.JwtUtils;
import bit.springblogdemo.common.util.SecurityUtil;
import bit.springblogdemo.mapper.UserInfoMapper;
import bit.springblogdemo.pojo.dataobject.BlogInfo;
import bit.springblogdemo.pojo.dataobject.UserInfo;
import bit.springblogdemo.pojo.request.UserLoginRequest;
import bit.springblogdemo.pojo.response.BlogInfoResponse;
import bit.springblogdemo.pojo.response.UserInfoResponse;
import bit.springblogdemo.pojo.response.UserLoginResponse;
import bit.springblogdemo.service.BlogService;
import bit.springblogdemo.service.UserService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BlogService blogService;

    @Override
    public UserLoginResponse checkPassword(UserLoginRequest userLoginRequest) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(UserInfo::getUserName,userLoginRequest.getUserName()).eq(UserInfo::getPassword,userLoginRequest.getPassword());
        queryWrapper.lambda().eq(UserInfo::getUserName, userLoginRequest.getUserName()).eq(UserInfo::getDeleteFlag,0);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if(userInfo==null){
            throw new BlogException("用户不存在");
        }
//        if(!userLoginRequest.getPassword().equals(userInfo.getPassword())){
//            throw new BlogException("用户密码错误");
//        }
        if(!SecurityUtil.checkPassword(userLoginRequest.getPassword(),userInfo.getPassword())){
            throw new BlogException("用户密码错误");
        }

        Map<String,Object> map=new HashMap<>();
        map.put("id",userInfo.getId());
        map.put("name",userInfo.getUserName());
        String token= JwtUtils.getToken(map);
        return new UserLoginResponse(userInfo.getId(),token);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag,0)
                .eq(UserInfo::getId,userId);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        return BeanUtilTrans.trans(userInfo);
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        //根据博客id获取博客信息，包括作者id
        BlogInfo blogInfo=blogService.getBlogInfo(blogId);
        if(blogInfo==null||blogInfo.getUserId()<=0){
            throw new BlogException("博客不存在");
        }
        //根据作者id,获取作者信息
        return getUserInfo(blogInfo.getUserId());
    }
}
